﻿
@{
    ViewBag.Title = "Kpi目標";
    ViewBag.PageInfo = "Kpi/KpiMain";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@*右鍵菜單*@
<style>
    #kpimenu {
        display: none;
        /*height: 320px;*/
        width: 240px;
        position: absolute;
        z-index: 9999;
        background-color: #ffffff;
        border: 1px solid #ffffff;
        border-radius: 8px;
        box-shadow: 2px 2px 8px 2px #c4c4c4;
    }

    .kpimenu-item {
        height: 35px;
        line-height: 35px;
        padding: 0 10px;
        cursor: default;
    }

        .kpimenu-item:hover {
            border-radius: 8px;
            background-color: #f1f1f1;
        }
</style>
<div id="kpimenu">
</div>
<script>
    var width = window.innerWidth;
    var height = window.innerHeight;
    //重新计算窗口大小
    window.addEventListener('resize', () => {
        width = window.innerWidth;
        height = window.innerHeight;
    })
    var kpimenu = document.querySelector("#kpimenu");
    window.oncontextmenu = function (e) {
        //取消瀏覽器默認右鍵菜單
        e.preventDefault();
        var tableTitle = $("#KpiDataTd table thead tr")[0].children;
        var data = "";
        for (var i = 3; i < tableTitle.length - 1; i++) {
            if (kpimenu.innerHTML == '\n') {
                data += '<div class="kpimenu-item" data-id="' + i + '"><input class="kpicheck-item" type="checkbox" checked="checked" onchange="kpiHideCol(' + i + ', event)" />&nbsp;&nbsp;' + tableTitle[i].innerHTML.replace("<br>", "") + '</div>';
            } else {
                if (kpimenu.children[i - 3].children[0].checked) {
                    data += '<div class="kpimenu-item" data-id="' + i + '"><input class="kpicheck-item" type="checkbox" checked="checked" onchange="kpiHideCol(' + i + ', event)" />&nbsp;&nbsp;' + tableTitle[i].innerHTML.replace("<br>", "") + '</div>';
                } else {
                    data += '<div class="kpimenu-item" data-id="' + i + '"><input class="kpicheck-item" type="checkbox" onchange="kpiHideCol(' + i + ', event)" />&nbsp;&nbsp;' + tableTitle[i].innerHTML.replace("<br>", "") + '</div>';
                }
            }
        }
        kpimenu.innerHTML = data;

        //根據鼠標右鍵位置定位
        if (e.pageX + 240 > width) {
            kpimenu.style.left = (width - 260) + "px";
        } else {
            kpimenu.style.left = e.pageX + "px";
        }
        if (e.pageY + 550 > height) {
            kpimenu.style.top = (height - 550) + "px";
        } else {
            kpimenu.style.top = e.pageY + "px";
        }
        //顯示菜單
        kpimenu.style.display = "block";
    }
    window.onclick = function (e) {
        //點擊（非右鍵菜單範圍）關閉
        if (e.target.className != "kpimenu-item" && e.target.className != "kpicheck-item") {
            kpimenu.style.display = "none";
        }
    }
    window.onmousewheel = function (e) {
        //滑動滾輪關閉
        kpimenu.style.display = "none";
    }
    //監聽菜單點擊
    window.addEventListener("click", function (e) {
        if (e.target.dataset.id) {
            kpimenu.children[e.target.dataset.id - 3].children[0].checked = !kpimenu.children[e.target.dataset.id - 3].children[0].checked;
            kpiHideCol(e.target.dataset.id, kpimenu.children[e.target.dataset.id - 3].children[0].checked)
        }
        //switch (e.target.dataset.id) {
        //    case "1": break;
        //}
    });
    //table列隱藏
    function kpiHideCol(colIndex, event) {
        var checked;
        if (event == true || event == false) {
            checked = event;
        } else {
            checked = event.target.checked;
        }
        var thead = $("#KpiDataTd table thead tr")[0].children;
        var tbody = $("#KpiDataTd table tbody tr");
        //隱藏thead
        thead[colIndex].hidden = !checked;
        //隱藏tbody
        for (var i = 0; i < tbody.length; i++) {
            tbody[i].children[colIndex].hidden = !checked;
        }
    }
    //刷新數據後隱藏會失效，table每次渲染完後檢查一遍，若有失效則重新隱藏
    function reloadHide() {
        if (kpimenu.innerHTML != '\n') {
            for (var j = 0; j < kpimenu.children.length; j++) {
                kpiHideCol(j + 3, kpimenu.children[j].children[0].checked);
            }
        }
    }
</script>

@*界面主體*@
<div style="position: fixed; margin-top: -260px; background-color: white; width: 100%; z-index: 100;">
    <div style="border: 4px solid #92d050; width: 80%; height: 180px; margin: auto; margin-top: 20px; border-radius: 10px;">
        <table style="width: 100%; margin-top:10px;">
            <tr style="height:50px;">
                <td style="width: 10%; text-align: right;">域：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtContract" type="text" value="@ViewBag.Contract" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">年度：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtYear" type="text" value="@DateTime.Now.Year" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">NO：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiNo" type="text" style="height:25px;width:162px;" />
                </td>
            </tr>
            <tr>
                <td style="width: 10%; text-align: right;">流程：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiDesc" type="text" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">績效指標：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiTarget" type="text" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">部門：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiDept" aria-label="TxtKpiDept" style="height:25px;width:162px;">
                        <option value=""></option>
                        @{
                            foreach (System.Data.DataRow item in ViewBag.Dept)
                            {
                                <option value="@item["DEPT_ID"].ToString()">@item["DEPT_DESC"].ToString()</option>
                            }
                        }
                    </select>
                </td>
            </tr>
            <tr style="height:50px;">
                <td style="width: 10%; text-align: right;">版本號：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiVersion" type="number" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">趨勢：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiTrend" aria-label="TxtKpiTrend" style="height:25px;width:162px;">
                        <option value=""></option>
                        <option value="↑">↑</option>
                        <option value="—">—</option>
                        <option value="↓">↓</option>
                    </select>
                </td>
                <td style="width: 10%; text-align: right;">狀態：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiStatus" aria-label="TxtKpiStatus" style="height:25px;width:162px;">
                        <option value=""></option>
                        <option value="Release">Release</option>
                        <option value="Close">Close</option>
                    </select>
                </td>
            </tr>
        </table>
    </div>
    <div style="text-align: left; margin-top: 15px; margin-left:15%; width: 80%; height: 40px;">
        <input id="BtnKpiSearch" type="button" value="查&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;詢" style="width: 100px; height: 25px;" onclick="btnKpiSearchClick('FP')" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <input id="BtnKpiSave" type="button" value="保&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;存" style="width: 100px; height: 25px;" onclick="saveKpiData()" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        @{
            if (Session["PERMISSIONS"].ToString() == "1")
            {
                <input id="BtnKpiLock" type="button" value="QA鎖定/取消" style="width: 100px; height: 25px;" onclick="BtnKpiLockClick()" />
                <span id="kpilock" style="color:red;"></span>
                <input id="BtnKpiFlowIni" type="button" value="啟動Flow簽核" style="width: 100px; height: 25px;" onclick="BtnKpiFlowIniClick()" />
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <input id="BtnKpiClose" type="button" value="確定/取消" style="width: 100px; height: 25px;" onclick="BtnKpiCloseClick()" hidden="hidden" />
                <input id="BtnKpiGen" type="button" value="生成下一年度" style="width: 100px; height: 25px;" onclick="btnKpiGen()" />
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <input id="BtnKpiMonth" type="button" value="生成月度數據" style="width: 100px; height: 25px;" onclick="btnKpiMonth()" />
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
            }
        }
        <input id="BtnVersion" type="button" value="版本更新" style="width: 100px; height: 25px;" onclick="btnVersion()" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <input id="BtnReportData" type="button" value="導出數據" style="width: 100px; height: 25px;" onclick="ReportData()" />
    </div>
</div>
<div style="text-align: center; margin-top: 260px; margin-left: 10%; width: 80%; overflow: auto; border-radius: 5px; z-index: 99;">
    <div id="KpiDataTd" style="text-align: center; width: 100%; height: 586px;">
        @{
            System.Data.DataTable kpiData = ViewBag.KpiData;
            if (kpiData.Rows.Count > 0)
            {
                <table style="width: 100%; border-left: 1px solid #507cd1; border-right: 1px solid #507cd1;">
                    <thead style="position:sticky;top:0;">
                        <tr style="background-color:#507cd1; font-size:18px; color: white; font-weight:bold; height:40px;">
                            <td hidden="hidden">IS_UPDATE</td>
                            <td hidden="hidden">KPI_ID</td>
                            <td width="4%"><input id="kpiTcb" type="checkbox" aria-label="kpiTcb" onchange="kpiTcbChange(event)" /></td>
                            <td width="4%">版本號</td>
                            <td width="4%">域</td>
                            <td width="4%">年度</td>
                            <td width="4%">NO</td>
                            <td width="12%">流程</td>
                            <td width="12%">績效指標</td>
                            <td width="6%">上年度<br />KPI指標</td>
                            <td width="6%">本年度<br />KPI指標</td>
                            <td width="4%">單位</td>
                            <td width="5%">趨勢</td>
                            <td width="5%">數值趨勢</td>
                            <td width="15%">公式</td>
                            <td width="5%">衡量頻率</td>
                            <td width="5%">狀態</td>
                            <td width="5%">流程<br />負責人</td>
                            <td hidden="hidden">RNUM</td>
                        </tr>
                    </thead>
                    <tbody>
                        @{
                            int colorIndex = 1;
                            string color;
                            foreach (System.Data.DataRow item in kpiData.Rows)
                            {
                                color = colorIndex % 2 == 1 ? "#eff3fb" : "#ffffff";
                                <tr style="background-color:@color; height:50px;">
                                    <td hidden="hidden">N</td>
                                    <td hidden="hidden">@item["KPI_ID"].ToString()</td>
                                    <td><input class="kpiDcb" type="checkbox" aria-label="kpiDcb" onchange="kpiDcbChange(event)" /></td>
                                    <td>@item["VERSION_NO"].ToString()</td>
                                    <td>@item["SITE"].ToString()</td>
                                    <td>@item["KPI_YEAR"].ToString()</td>
                                    <td>@item["KPI_NO"].ToString()</td>
                                    <td>@item["KPI_DESC"].ToString()</td>
                                    <td>@item["KPI_TARGET"].ToString()</td>
                                    <td>@item["PRE_KPI_VALUE"].ToString()</td>
                                    <td>
                                        @{
                                            if (item["IS_LOCK"].ToString() == "Y" || item["RNUM"].ToString() != "1")
                                            {
                                                <input type="text" value="@item["KPI_VALUE"].ToString()" style="width:70px;height:25px;" onchange="updateKpiFlag(event)" disabled="disabled" />
                                            }
                                            else
                                            {
                                                <input type="text" value="@item["KPI_VALUE"].ToString()" style="width:70px;height:25px;" onchange="updateKpiFlag(event)" />
                                            }
                                        }
                                    </td>
                                    <td>@item["UOM_NM"].ToString()</td>
                                    <td>@item["VALUE_TREND"].ToString()</td>
                                    <td>@item["TREND_DESC"].ToString()</td>
                                    <td>@item["KPI_FUNC"].ToString()</td>
                                    <td>@item["FREQ_DESC"].ToString()</td>
                                    <td>@item["STATUS_E"].ToString()</td>
                                    <td>@item["KPI_OWNER"].ToString()</td>
                                    <td hidden="hidden">@item["RNUM"].ToString()</td>
                                </tr>
                                colorIndex++;
                            }
                        }
                    </tbody>
                    <tfoot style="position: sticky; bottom: 0;">
                        <tr style="background-color:#507cd1; font-size:15px; color: white; height:35px;">
                            <td colspan="16" style="text-align:left;">
                                &#12288;&#12288;&#12288;
                                第:
                                <span id="pagesIndex">@ViewBag.PagesIndex</span>
                                頁/共:
                                <span>@ViewBag.PagesCount</span>
                                頁
                                &#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;
                                &#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;
                                &#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;
                                <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClick('FP')">首頁</a>
                                <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClick('PP')">上一頁</a>
                                <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClick('NP')">下一頁</a>
                                <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClick('LP')">尾頁</a>
                                轉到第
                                <input id="pagesTo" type="number" value="@ViewBag.PagesIndex" style="height:20px;width:40px;color:black;" />
                                頁
                                <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClick('TP')">Go</a>
                                &#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;
                                &#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;
                                &#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;
                                每頁
                                <select id="pagesNum" style="height: 20px; width: 40px; color: black;" onchange="btnKpiSearchClick('FP')">
                                    @{
                                        int value = 0;
                                        for (int i = 1; i <= 5; i++)
                                        {
                                            value = i * 10;
                                            if (ViewBag.pagesNum == i * 10)
                                            {
                                                <option value="@value" selected="selected">@value</option>
                                            }
                                            else
                                            {
                                                <option value="@value">@value</option>
                                            }
                                        }
                                    }
                                </select>
                                筆/共
                                <span>@ViewBag.DataNums</span>
                                筆
                            </td>
                        </tr>
                    </tfoot>
                </table>
            }
            else
            {
                <h3>未查詢到數據！</h3>
            }
        }
    </div>
</div>

<script>
    //更新鎖定狀態
    function updateLockInfo() {
        //var site = $("#TxtContract").val();
        //var year = $("#TxtYear").val();
        //var site = "EMCHS";
        var year = new Date().getFullYear();
        $.ajax({
            type: "post",
            url: "/Kpi/IsLockSpan",
            data: {
                //site: site,
                year: year
            },
            success: function (data) {
                var result = JSON.parse(data);
                if (result.flag) {
                    $("#kpilock")[0].innerHTML = result.isLock;
                } else {
                    alert(result.msg);
                }
            }
        });
    }
    //查詢
    function btnKpiSearchClick(flipPage) {
        showLoading();
        $.ajax({
            type: "get",
            url: "/Kpi/BtnSearchClick",
            data: {
                txtKpiSite: $("#TxtContract").val(),
                txtKpiYear: $("#TxtYear").val(),
                txtKpiNo: $("#TxtKpiNo").val(),
                txtKpiDesc: $("#TxtKpiDesc").val(),
                txtKpiTarget: $("#TxtKpiTarget").val(),
                txtKpiDept: $("#TxtKpiDept").val(),
                txtKpiVersion: $("#TxtKpiVersion").val(),
                txtKpiTrend: $("#TxtKpiTrend").val(),
                txtKpiStatus: $("#TxtKpiStatus").val(),
                pagesIndex: $("#pagesIndex").text(),
                pagesNum: $("#pagesNum").val(),
                pagesTo: $("#pagesTo").val(),
                flipPage: flipPage
            },
            success: function (data) {
                updateLockInfo();
                $("#KpiDataTd").html(data);
                reloadHide();
                hideLoading();
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    function updateKpiFlag(event) {
        var row = event.target.parentNode.parentNode;
        row.cells[0].innerText = "Y"
    }
    //保存
    function saveKpiData() {
        const regex = /[^=><≥≤≧≦]/g;
        var tmpstr;
        
        var updateData = [];
        var KPI_ID;
        var SITE;
        var KPI_YEAR;
        var KPI_VALUE;
        var VERSION_NO;
        var kpiDataTd = $("#KpiDataTd tbody tr");
        for (var i = 0; i < kpiDataTd.length; i++) {
            //if (kpiDataTd[i].cells[0].innerText == "Y")
            if (kpiDataTd[i].cells[2].children[0].checked) {
                KPI_ID = kpiDataTd[i].cells[1].innerText;
                VERSION_NO = kpiDataTd[i].cells[3].innerText;
                SITE = kpiDataTd[i].cells[4].innerText;
                KPI_YEAR = kpiDataTd[i].cells[5].innerText;
                KPI_VALUE = kpiDataTd[i].cells[10].children[0].value;

                tmpstr = KPI_VALUE.replace(regex, "");
                if (kpiDataTd[i].cells[11].innerText == "%" && KPI_VALUE.replace(tmpstr, "") > 100) {
                    alert("單位為%時，數值必須小於等於100！");
                    return;
                }

                updateData.push(KPI_ID + "^" + SITE + "^" + KPI_YEAR + "^" + KPI_VALUE + "^" + VERSION_NO);
            }
        }
        if (updateData.length == 0) {
            alert("沒有數據需要保存！（請先選中首欄勾選框再點擊保存）");
            return;
        }
        showLoading();
        $.ajax({
            type: "post",
            url: "/Kpi/BtnKpiSaveClick",
            data: {
                updateData: updateData.join('&')
            },
            success: function (data) {
                hideLoading();
                var result = JSON.parse(data);
                if (result.flag) {
                    alert(result.msg);
                    btnKpiSearchClick('CP');
                } else {
                    alert(result.msg);
                }
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    //生成下一年度
    function btnKpiGen() {
        //var lock = $("#kpilock")[0].innerHTML;
        //if (lock.indexOf("未鎖定") > 0) {
        //    alert("未鎖定，無法生成下一年度數據！");
        //    return;
        //}
        var date = new Date();
        if (confirm("當前年度：" + date.getFullYear() + "\n確定生成下一年度[" + (date.getFullYear() + 1) + "]KPI目標數據？")) {
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/BtnKpiGenClick",
                data: {
                    //site: "EMCHS",
                    year: date.getFullYear()
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }
    //生成月度數據
    function btnKpiMonth() {
        var lock = $("#kpilock")[0].innerHTML;
        if (lock.indexOf("未鎖定") > 0) {
            alert("未鎖定，無法生成月度數據！");
            return;
        }
        var date = new Date();
        if (confirm("確定生成月度數據？")) {
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/BtnKpiMonthClick",
                data: {
                    //site: "EMCHS",
                    year: date.getFullYear()
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }
    //關閉/取消
    function BtnKpiCloseClick() {
        var updateData = [];
        var KPI_ID;
        var SITE;
        var KPI_YEAR;
        var VERSION_NO;
        var kpiDataTd = $("#KpiDataTd tbody tr");
        for (var i = 0; i < kpiDataTd.length; i++) {
            if (kpiDataTd[i].cells[2].children[0].checked) {
                KPI_ID = kpiDataTd[i].cells[1].innerText;
                VERSION_NO = kpiDataTd[i].cells[3].innerText;
                SITE = kpiDataTd[i].cells[4].innerText;
                KPI_YEAR = kpiDataTd[i].cells[5].innerText;
                updateData.push(KPI_ID + "^" + SITE + "^" + KPI_YEAR + "^" + VERSION_NO);
            }
        }
        if (updateData.length == 0) {
            alert("請選擇至少一條數據！");
            return;
        }
        if (confirm("確認變更狀態？")) {
            //關閉則打開，未關閉則關閉
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/KpiCloseOrCancel",
                data: {
                    //site: "EMCHS",
                    data: updateData.join('&')
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                        btnKpiSearchClick('FP');
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }
    //鎖定/取消
    function BtnKpiLockClick() {
        var date = new Date();
        //查詢是否鎖定
        showLoading();
        $.ajax({
            type: "post",
            url: "/Kpi/IsLock",
            data: {
                //site: "EMCHS",
                year: date.getFullYear()
            },
            success: function (data) {
                hideLoading();
                var result = JSON.parse(data);
                if (result.flag) {
                    var prompt = "確認鎖定[" + date.getFullYear() + "]年度KPI目標？";
                    if (result.isLock) {
                        prompt = "[" + date.getFullYear() + "]年度KPI目標已鎖定，確認打開？";
                    }
                    if (confirm(prompt)) {
                        //鎖定則打開，未鎖定則鎖定
                        showLoading();
                        $.ajax({
                            type: "post",
                            url: "/Kpi/KpiLockOrCancel",
                            data: {
                                //site: "EMCHS",
                                year: date.getFullYear(),
                                flag: result.isLock ? "lock" : "cancel"
                            },
                            success: function (data) {
                                hideLoading();
                                var result = JSON.parse(data);
                                if (result.flag) {
                                    alert(result.msg);
                                    updateLockInfo();
                                    btnKpiSearchClick('FP');
                                } else {
                                    alert(result.msg);
                                }
                            },
                            error: function (err) {
                                hideLoading();
                            }
                        });
                    }
                } else {
                    alert(result.msg);
                }
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    //版本更新
    function btnVersion() {
        var lock = $("#kpilock")[0].innerHTML;
        if (lock.indexOf("已鎖定") > 0) {
            alert("已鎖定，無法更新版本！");
            return;
        }
        var updateData = [];
        var KPI_ID;
        var kpiDataTd = $("#KpiDataTd tbody tr");
        for (var i = 0; i < kpiDataTd.length; i++) {
            if (kpiDataTd[i].cells[2].children[0].checked) {
                if (kpiDataTd[i].cells[18].innerText != "1") {
                    alert("只能更新最新版本！");
                    return;
                }
                KPI_ID = kpiDataTd[i].cells[1].innerText;
                updateData.push(KPI_ID);
            }
        }
        if (updateData.length == 0) {
            alert("請選擇一條數據！");
            return;
        }
        if (confirm("確認更新版本？")) {
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/BtnKpiVersionClick",
                data: {
                    updateData: updateData.join('&')
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                        btnKpiSearchClick('CP');
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }
    //啟動Flow簽核
    function BtnKpiFlowIniClick() {
        var lock = $("#kpilock")[0].innerHTML;
        if (lock.indexOf("未鎖定") > 0) {
            alert("未鎖定，無法啟動簽核");
            return;
        }
        var kpi_year = new Date().getFullYear();
        if (confirm("確認啟動Flow簽核【" + kpi_year + "年度】？")) {
            //關閉則打開，未關閉則關閉
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/KpiFlowIni",
                data: {
                    //site: "EMCHS",
                    year: kpi_year
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                        btnKpiSearchClick('FP');
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }
    //導出數據
    function ReportData() {
        var tableTitle = $("#KpiDataTd table thead tr")[0].children;
        var title = [];
        var index = [];
        for (var i = 3; i < tableTitle.length; i++) {
            if (!tableTitle[i].hidden) {
                title.push(tableTitle[i].innerHTML.replace("<br>", ""));
                index.push(i - 3);
            }
        }
        showLoading();

        $.ajax({
            type: "post",
            url: "/Kpi/ExportTarget",
            data: {
                txtKpiSite: $("#TxtContract").val(),
                txtKpiYear: $("#TxtYear").val(),
                txtKpiNo: $("#TxtKpiNo").val(),
                txtKpiDesc: $("#TxtKpiDesc").val(),
                txtKpiTarget: $("#TxtKpiTarget").val(),
                txtKpiDept: $("#TxtKpiDept").val(),
                txtKpiVersion: $("#TxtKpiVersion").val(),
                txtKpiTrend: $("#TxtKpiTrend").val(),
                txtKpiStatus: $("#TxtKpiStatus").val(),
                index: index.join(',')
            },
            success: function (data) {
                hideLoading();
                //downloadFile2(data, 'KpiTarget.xlsx', 'application/xlsx');
                var result = JSON.parse(data);
                downloadFile(result.msg);
                setTimeout(function () {
                    deleteFile(result.msg);
                }, 5000);
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    //下載文件
    function downloadFile(fielPath) {
        var url = window.location.origin + "/Template/" + fielPath + "/Kpi目標匯總表.xlsx";
        window.open(url);
    }
    //刪除文件
    function deleteFile(fielPath) {
        $.ajax({
            type: "post",
            url: "/Kpi/DeleteTemplate",
            data: {
                filePath: fielPath
            },
            success: function (data) { },
            error: function (err) { }
        });
    }
    //下載文件流
    function downloadFile2(data, filename, type) {
        // 创建 Blob 对象
        const blob = new Blob([data], { type: type });

        // 判断当前浏览器是否是IE，由于IE是没有download 方法的，需要用msSaveBlob() 或 msSaveOrOpenBlob()
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // 兼容IE
            window.navigator.msSaveOrOpenBlob(blob, filename)
        } else {
            // 创建 URL 对象
            const url = URL.createObjectURL(blob);

            // 创建链接
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;

            // 模拟点击链接进行下载
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            // 释放 URL 对象
            URL.revokeObjectURL(url);
        }
    }
    //標題全選
    function kpiTcbChange(event) {
        var kpiDcb = $(".kpiDcb");
        for (var i = 0; i < kpiDcb.length; i++) {
            kpiDcb[i].checked = event.srcElement.checked;
        }
    }
    //內容全選
    function kpiDcbChange(event) {
        if (event.srcElement.checked) {
            var kpiDcb = $(".kpiDcb");
            var checkeddata = 0;
            for (var i = 0; i < kpiDcb.length; i++) {
                if (kpiDcb[i].checked) {
                    checkeddata++;
                }
            }
            if (checkeddata == kpiDcb.length && checkeddata > 0) {
                $("#kpiTcb")[0].checked = true;
            }
        } else {
            $("#kpiTcb")[0].checked = event.srcElement.checked;
        }
    }
    $(function () {
        updateLockInfo();
    });
</script>